iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 23
0
Modern Web

Zero to hero with React.js系列 第 23

【Day 23 React】Redux 做遊戲角色陣容應用程式——趴水

  • 分享至 

  • xImage
  •  

接續昨天在 index.js 寫完 reducer 的程式碼,現在要把這些程式碼分別放進各自的 reducer 裡,實現最結構化的撰寫模式。我們在 reducer 資料夾裡,新增 characters_reducer.jsheros_reducer.js

characters_reducer 複製貼上最簡單!但記得要在最後一行 export export default characters;

import characters_json from '../data/characters.json';
import { ADD_CHARACTER } from '../actions';

function characters(state = characters_json, action){
    switch(action.type){
        case ADD_CHARACTER:
            let characters = state.filter(item => item.id !== action.id );
            return characters;
        default:
          return state;
    }
}

export default characters;

同樣地,舉一反三,在 heros_reducer 也是做一樣的動作~

import { ADD_CHARACTER } from '../actions';
import characters_json from '../data/characters.json';

function heros(state = [], action){
    switch(action.type) {
      case ADD_CHARACTER:
        let heros = [...state, createCharacter(action.id)];
        return heros;
      default:
        return state;
    }
}

function createCharacter(id) {
   let character = characters_json.find(c => c.id === id);
   return character;
}

export default heros;

現在 index.js 的樣貌~程式碼乾淨許多!

import { combineReducers } from 'redux';

function createCharacter(id) {
   let character = characters_json.find(c => c.id === id);
   return character;
}

const rootReducer = combineReducers({
    characters,
    heros
})

export default rootReducer;

但是別忘了,剛剛移到 reducer 裡的 characters 和 hero 要 import 回來

import characters from './characters_reducer.js';
import heros from './heros_reducer.js'; 

並把 createCharacter function 放到 helper.js

import characters_json from '../data/characters.json';

export function createCharacter(id) {
   let character = characters_json.find(c => c.id === id);
   return character;
}

因為 heros reducercreateCharacter 作用有關聯性,因此我們要在 heros_reducer.js import createCharacter

import { createCharacter } from './helper';

上一篇
【Day 22 React】Redux 做遊戲角色陣容應用程式——趴兔
下一篇
【Day 24 React】Redux 做遊戲角色陣容應用程式——趴四
系列文
Zero to hero with React.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言